#!/bin/bash
# macOS 打包脚本
# IoT工具集 - 统一调试平台

set -e

echo "=================================="
echo "  IoT工具集 - macOS 打包工具"
echo "=================================="
echo ""

# 初始化 conda
eval "$(conda shell.bash hook)"

# 激活 tool 环境
echo "🔄 激活 conda tool 环境..."
conda activate tool

echo "✅ 当前 conda 环境: $CONDA_DEFAULT_ENV"
echo ""

echo "✅ 当前工作目录: $(pwd)"
echo ""

# 检查依赖
echo "📦 检查依赖包..."
echo "  - 检查 PyInstaller..."
pip list | grep -q PyInstaller || pip install PyInstaller

echo "  - 检查 PyQt6..."
pip list | grep -q PyQt6 || pip install PyQt6

echo "  - 检查其他依赖..."
pip list | grep -q pymodbus || pip install pymodbus
pip list | grep -q pyserial || pip install pyserial

echo "✅ 所有依赖检查完成"
echo ""

# 清理旧的构建文件
echo "🧹 清理旧的构建文件..."
rm -rf build dist *.spec 2>/dev/null || true
echo "✅ 清理完成"
echo ""

# 设置应用信息
APP_NAME="IoT工具集"
BUNDLE_ID="com.iot.util.toolkit"
MAIN_FILE="main_window.py"
ICON_FILE="app_icon.icns"

# 检查图标文件
if [ ! -f "$ICON_FILE" ]; then
    echo "❌ 图标文件不存在: $ICON_FILE"
    exit 1
fi

echo "📦 开始打包..."
echo "  应用名称: $APP_NAME"
echo "  主文件: $MAIN_FILE"
echo "  图标: $ICON_FILE"
echo ""

# 运行 PyInstaller
echo "🔨 执行 PyInstaller 打包..."
pyinstaller \
    --noconfirm \
    --onedir \
    --windowed \
    --name "$APP_NAME" \
    --icon="$ICON_FILE" \
    --add-data="gui:gui" \
    --add-data="utils:utils" \
    --hidden-import=PyQt6 \
    --hidden-import=PyQt6.QtCore \
    --hidden-import=PyQt6.QtGui \
    --hidden-import=PyQt6.QtWidgets \
    --hidden-import=PyQt6.QtNetwork \
    --hidden-import=pyserial \
    --hidden-import=pymodbus \
    --hidden-import=serial \
    --hidden-import=modbus_tk \
    --hidden-import=modbus_tk.defines \
    --hidden-import=modbus_tk.modbus \
    --hidden-import=modbus_tk.modbus_rtu \
    --hidden-import=modbus_tk.modbus_tcp \
    --collect-all=pymodbus \
    --collect-all=modbus_tk \
    --collect-all=serial \
    "$MAIN_FILE"

# 检查打包结果
BUNDLE_PATH="dist/$APP_NAME.app"

if [ -d "$BUNDLE_PATH" ]; then
    echo ""
    echo "✅ 打包成功！"
    echo "📦 应用位置: $BUNDLE_PATH"
    echo ""
    echo "📊 应用信息:"
    echo "  大小: $(du -sh "$BUNDLE_PATH" | cut -f1)"
    echo "  文件数: $(find "$BUNDLE_PATH" -type f | wc -l)"
    echo ""
    echo "🚀 运行应用:"
    echo "   open \"$BUNDLE_PATH\""
    echo ""
    echo "📋 在 Finder 中显示:"
    echo "   open -R \"$BUNDLE_PATH\""
    echo ""
else
    echo "❌ 打包失败！"
    echo "请检查错误信息并重试"
    exit 1
fi
